package com.kefu.call.service;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.kefu.call.mapper.ActivityBaseInfoMapper;
import com.kefu.call.mapper.ActivityInventoryInfoMapper;
import com.kefu.call.model.ActivityBaseInfo;
import com.kefu.call.model.ActivityInventoryInfo;
import com.kefu.call.vo.ActivityBaseInfoInsertVo;
import com.kefu.call.vo.ActivityBaseInfoSearchVo;
import com.kefu.call.vo.ActivityBaseInfoUpdateVo;
import com.kefu.common.context.KefuContext;
import com.kefu.common.exception.BusinessException;
import com.kefu.common.service.AbstractKefuService;
import com.kefu.common.util.JacksonUtil;

import cn.hutool.core.util.StrUtil;

/**
 * @author francis
 * @date 2021/05/22
 */
@Service
@Transactional
public class ActivityBaseInfoService  extends AbstractKefuService<ActivityBaseInfo> {
    @Resource
    protected ActivityBaseInfoMapper activityBaseInfoMapper;
    @Resource
    protected ActivityInventoryInfoMapper activityInventoryInfoMapper;

	
	public ActivityBaseInfo update(ActivityBaseInfo info) {
		activityBaseInfoMapper.updateByPrimaryKeySelective(info);
		if (Objects.isNull(info) || Objects.isNull(info.getActivityStatus())) {
			return info;
		}
		Map<String,Object> search = Maps.newHashMap();
		search.put("activityId",info.getActivityId());
		if(info.getActivityStatus()==1) {//将状态为暂停得清单修改为启用
			search.put("newDataStatus",1);
			search.put("oldDataStatus",2);
		}
		if(info.getActivityStatus()==2) {//将状态为启用得清单改外暂停
			search.put("newDataStatus",2);
			search.put("oldDataStatus",1);
		}
		if(info.getActivityStatus()==3) {//将状态为暂停得清单改外停用
			search.put("newDataStatus",0);
			search.put("oldDataStatus",2);
		}
		activityInventoryInfoMapper.updateInventoryByActivityIdAndDataStatus(search);
		return info;
	}

	
	public void deleteById(String id) {
		ActivityBaseInfo info = activityBaseInfoMapper.selectByPrimaryKey(id);
		if (Objects.nonNull(info) && Objects.nonNull(info.getDataStatus()) && 0 == info.getDataStatus()) {
			throw BusinessException.msg("活动已经被删除");
		}
		List<ActivityInventoryInfo> list = activityInventoryInfoMapper.selectList(Wrappers.lambdaQuery(ActivityInventoryInfo.class)
						.eq(ActivityInventoryInfo::getActivityId, id)
						.eq(ActivityInventoryInfo::getDataStatus, 1));
		if (null != list && list.size() > 0) {
			throw BusinessException.msg("存在清单不能删除");
		}
		info.setDataStatus(0);
		update(info);
	}

	
	public ActivityBaseInfo findById(String id) {
		return activityBaseInfoMapper.findById(id);
	}

	
	public Page<ActivityBaseInfo> queryActivityList(ActivityBaseInfoSearchVo search) {
		search.setTenantId(KefuContext.getKefuContext().getTenantId());
		Page<ActivityBaseInfo> page = new Page<>(search.getPageNo(), search.getPageSize(), true);
		if (StrUtil.isNotBlank(search.getOrderField()) && StrUtil.isNotBlank(search.getOrder().name())) {
			OrderItem orderItem =StrUtil.equalsIgnoreCase(search.getOrder().name(), "ASC")?
					OrderItem.asc(StrUtil.toUnderlineCase(search.getOrderField())):
					OrderItem.desc(StrUtil.toUnderlineCase(search.getOrderField()));
			page.addOrder(orderItem);
		}else {
			OrderItem orderItem = OrderItem.desc("update_time");
			page.addOrder(orderItem);
		}
		page = activityBaseInfoMapper.selectActivityBaseInfo(page, search);
		return page;
	}

	
	public String addActivity(ActivityBaseInfoInsertVo activityBaseInfoVo) {
		List<ActivityBaseInfo> list = activityBaseInfoMapper.selectList(
				Wrappers.lambdaQuery(ActivityBaseInfo.class)
				.eq(ActivityBaseInfo::getActivityName, activityBaseInfoVo.getActivityName())
				.eq(ActivityBaseInfo::getTenantId, KefuContext.getTid()));
		if (null != list && list.size() > 0) {
			throw BusinessException.msg("活动已经存在");
		}
		if (1 == activityBaseInfoVo.getPaperOpen() && StrUtil.isBlank(activityBaseInfoVo.getPaperId())) {
			throw BusinessException.msg("请先选择问卷");
		}
		ActivityBaseInfo info = activityBaseInfoVo.convert();
		int i = activityBaseInfoMapper.insert(info);
		logger.info("添加外呼任务[{}]:{}", i, JacksonUtil.toString(info));
		return info.getActivityId();
	}

	
	public String updateActivity(ActivityBaseInfoUpdateVo activityBaseInfoVo) {
		List<ActivityBaseInfo> list = activityBaseInfoMapper.selectList(Wrappers.lambdaQuery(ActivityBaseInfo.class)
				.eq(ActivityBaseInfo::getActivityName, activityBaseInfoVo.getActivityName())
				.eq(ActivityBaseInfo::getTenantId, KefuContext.getKefuContext().getTenantId()));
		if (null != list && list.size() > 0) {
			list.forEach(i -> {
				if (!i.getActivityId().equals(activityBaseInfoVo.getActivityId())) {
					throw BusinessException.msg("活动已经存在");
				}
			});
		}
		if (1 == activityBaseInfoVo.getPaperOpen() && StrUtil.isBlank(activityBaseInfoVo.getPaperId())) {
			throw BusinessException.msg("请先选择问卷");
		}
		ActivityBaseInfo info = activityBaseInfoVo.convert();
		int i = activityBaseInfoMapper.updateByPrimaryKeySelective(info);
		 
		logger.info("更新活动[{}]:{}", i, JacksonUtil.toString(info));
		return info.getActivityId();
	}
}
